"""
数据源配置管理API
"""

from flask import Blueprint, request
from app.utils.response import success_response, error_response, paginate_response
from app.models.data_source import DataSource as DataSourceModel
from app.services.data_source import DataSourceFactory
from app import db

data_sources_bp = Blueprint('data_sources', __name__, url_prefix='/api/data-sources')


@data_sources_bp.route('', methods=['POST'])
def create_data_source():
    """
    创建数据源配置
    
    请求体:
    {
        "name": "数据源名称",
        "type": "excel",  # excel/json/mysql
        "config": {
            "file_path": "/path/to/file.xlsx",
            "sheet_name": "Sheet1"
        },
        "project_id": 1  # 可选
    }
    """
    try:
        data = request.get_json()
        
        # 验证必需字段
        required_fields = ['name', 'type', 'config']
        for field in required_fields:
            if field not in data:
                return error_response(f"缺少必需字段: {field}")
        
        name = data['name']
        source_type = data['type']
        config = data['config']
        project_id = data.get('project_id')
        
        # 验证数据源配置
        try:
            data_source = DataSourceFactory.create(source_type, config)
            # 测试读取（只读取前1条验证）
            test_data = data_source.read_data()
            if not test_data:
                return error_response("数据源为空，请检查配置")
        except Exception as e:
            return error_response(f"数据源配置验证失败: {str(e)}")
        
        # 保存到数据库
        import json
        data_source_model = DataSourceModel(
            name=name,
            type=source_type,
            config=json.dumps(config, ensure_ascii=False),
            project_id=project_id
        )
        db.session.add(data_source_model)
        db.session.commit()
        
        return success_response({
            'id': data_source_model.id,
            'name': data_source_model.name,
            'type': data_source_model.type,
            'created_at': data_source_model.created_at.strftime('%Y-%m-%d %H:%M:%S')
        })
        
    except Exception as e:
        db.session.rollback()
        return error_response(f"创建数据源失败: {str(e)}")


@data_sources_bp.route('', methods=['GET'])
def get_data_sources():
    """
    获取数据源列表
    
    查询参数:
    - project_id: 项目ID（可选）
    - page: 页码（默认1）
    - page_size: 每页数量（默认10）
    """
    try:
        project_id = request.args.get('project_id', type=int)
        page = request.args.get('page', 1, type=int)
        page_size = request.args.get('page_size', 10, type=int)
        
        query = DataSourceModel.query
        
        if project_id:
            query = query.filter_by(project_id=project_id)
        
        # 分页
        pagination = query.order_by(DataSourceModel.created_at.desc()).paginate(
            page=page, per_page=page_size, error_out=False
        )
        
        items = []
        for ds in pagination.items:
            items.append({
                'id': ds.id,
                'name': ds.name,
                'type': ds.type,
                'project_id': ds.project_id,
                'created_at': ds.created_at.strftime('%Y-%m-%d %H:%M:%S')
            })
        
        return paginate_response(items, page, page_size, pagination.total)
        
    except Exception as e:
        return error_response(f"查询数据源列表失败: {str(e)}")


@data_sources_bp.route('/<int:id>', methods=['GET'])
def get_data_source(id):
    """
    获取数据源详情
    """
    try:
        data_source = DataSourceModel.query.get(id)
        
        if not data_source:
            return error_response("数据源不存在", 404)
        
        import json
        return success_response({
            'id': data_source.id,
            'name': data_source.name,
            'type': data_source.type,
            'config': json.loads(data_source.config),
            'project_id': data_source.project_id,
            'created_at': data_source.created_at.strftime('%Y-%m-%d %H:%M:%S')
        })
        
    except Exception as e:
        return error_response(f"查询数据源失败: {str(e)}")


@data_sources_bp.route('/<int:id>', methods=['DELETE'])
def delete_data_source(id):
    """
    删除数据源
    """
    try:
        data_source = DataSourceModel.query.get(id)
        
        if not data_source:
            return error_response("数据源不存在", 404)
        
        db.session.delete(data_source)
        db.session.commit()
        
        return success_response(None, "删除成功")
        
    except Exception as e:
        db.session.rollback()
        return error_response(f"删除数据源失败: {str(e)}")


@data_sources_bp.route('/<int:id>/preview', methods=['GET'])
def preview_data_source(id):
    """
    预览数据源数据（前10条）
    """
    try:
        data_source_model = DataSourceModel.query.get(id)
        
        if not data_source_model:
            return error_response("数据源不存在", 404)
        
        import json
        config = json.loads(data_source_model.config)
        
        # 创建数据源并读取数据
        data_source = DataSourceFactory.create(data_source_model.type, config)
        data = data_source.read_data()
        
        # 只返回前10条
        preview_data = data[:10] if len(data) > 10 else data
        
        return success_response({
            'total': len(data),
            'preview': preview_data,
            'fields': list(preview_data[0].keys()) if preview_data else []
        })
        
    except Exception as e:
        return error_response(f"预览数据失败: {str(e)}")


@data_sources_bp.route('/test-connection', methods=['POST'])
def test_connection():
    """
    测试数据源连接（主要用于MySQL）
    
    请求体:
    {
        "type": "mysql",
        "config": {
            "host": "localhost",
            "port": 3306,
            "user": "root",
            "password": "password",
            "database": "test"
        }
    }
    """
    try:
        data = request.get_json()
        
        if 'type' not in data or 'config' not in data:
            return error_response("缺少必需字段")
        
        source_type = data['type']
        config = data['config']
        
        # 创建数据源并测试
        if source_type == 'mysql':
            from app.services.data_source import MysqlDataSource
            data_source = MysqlDataSource(config)
            if data_source.test_connection():
                return success_response({'status': 'success', 'message': '连接成功'})
            else:
                return error_response("连接失败")
        else:
            # 其他类型尝试读取数据
            data_source = DataSourceFactory.create(source_type, config)
            data_source.read_data()
            return success_response({'status': 'success', 'message': '配置有效'})
        
    except Exception as e:
        return error_response(f"测试连接失败: {str(e)}")
